package com.example.webdemo.controller;

import com.example.webdemo.bean.product;
import com.example.webdemo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    private final ProductService productService;

    @Autowired
    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    // 创建商品
    @PostMapping
    public ResponseEntity<product> createProduct(@Valid @RequestBody product product) {
        product createdProduct = productService.createProduct(product);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdProduct);
    }

    // 更新商品
    @PutMapping("/{id}")
    public ResponseEntity<product> updateProduct(
            @PathVariable int id,
            @Valid @RequestBody product product) {
        product updatedProduct = productService.updateProduct(id, product);
        return ResponseEntity.ok(updatedProduct);
    }

    // 删除商品
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable int id) {
        productService.deleteProduct(id);
        return ResponseEntity.noContent().build();
    }

    // 获取单个商品
    @GetMapping("/{id}")
    public ResponseEntity<product> getProduct(@PathVariable int id) {
        product product = productService.getProductById(id);
        return ResponseEntity.ok(product);
    }

    // 获取所有商品
    @GetMapping("/all")
    public ResponseEntity<List<product>> getAllProducts() {
        List<product> products = productService.getAllProducts();
        return ResponseEntity.ok(products);
    }

    // 多条件搜索商品
    @GetMapping("/search")
    public ResponseEntity<List<product>> searchProducts(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) Integer status) {

        List<product> products = productService.searchProducts(name, category, status);
        return ResponseEntity.ok(products);
    }

    // 调整库存
    @PostMapping("/{id}/adjust-stock")
    public ResponseEntity<Void> adjustStock(
            @PathVariable int id,
            @RequestParam int quantity) {

        if (quantity > 0) {
            productService.increaseStock(id, quantity);
        } else if (quantity < 0) {
            productService.decreaseStock(id, -quantity);
        }
        return ResponseEntity.ok().build();
    }
}